package com.cz.basetool.ui_work.util.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectManger {

    public static Class getClassByName(String pkg) throws ClassNotFoundException {
        return ReflectManger.class.getClassLoader().loadClass(pkg);
    }

    public static Object invokeMethod(Class clazz, Object instance, String methodName, Class[] parms, Object[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method = clazz.getDeclaredMethod(methodName, parms);
        method.setAccessible(true);
        return method.invoke(instance, args);
    }

    public static Object getField(Class clazz, Object instance, String fieldName)  {
        try {
            Field field =  clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field.get(instance);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void setField(Class clazz, Object instance, String fieldName,Object fieldValue)  {
        try {
            Field field =  clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(instance,fieldValue);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}